<template>
  <div class="login-container">
    <div v-show="showHospital" class="hospital-title">
      蚌埠医学院第二附属医院卒中胸痛系统
    </div>
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
      :style="{ marginTop: showHospital ? '' : '35vh' }"
    >
      <div class="title-container">
        <div class="title">
          <img style="" src="~@/images/logo_u5.png" />
          <span>云智医</span>
        </div>
        <!-- <h3 class="title">{{ $t('login.title') }}</h3> -->
        <!-- <lang-select class="set-language" /> -->
      </div>

      <el-form-item prop="username" class="userInfo marginLR">
        <span class="svg-container"><svg-icon icon-class="user" /></span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入用户名"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip
        v-model="capsTooltip"
        content="大写锁定已开启"
        placement="right"
        manual
      >
        <el-form-item prop="password" class="userInfo marginLR">
          <span class="svg-container"><svg-icon icon-class="password" /></span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="请输入密码"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd"
            ><svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
          /></span>
        </el-form-item>
      </el-tooltip>
      <el-checkbox v-model="oRemember" class="marginLR">记住密码</el-checkbox>
      <el-button
        :loading="loading"
        type="primary"
        style="
          width: 80%;
          margin: 0 auto;
          margin-bottom: 30px;
          display: block;
          background-color: #1890ff;
        "
        @click.native.prevent="handleLogin"
      >
        登录
      </el-button>

      <!-- <div style="position:relative">
        <div class="tips">
          <span>{{ $t('login.username') }} : admin</span>
          <span>{{ $t('login.password') }} : {{ $t('login.any') }}</span>
        </div>
        <div class="tips">
          <span style="margin-right:18px;">{{ $t('login.username') }} : editor</span>
          <span>{{ $t('login.password') }} : {{ $t('login.any') }}</span>
        </div>

        <el-button
          class="thirdparty-button"
          type="primary"
          @click="showDialog=true"
        >{{ $t('login.thirdparty') }}</el-button>
      </div> -->
    </el-form>
    <!-- <el-dialog :title="$t('login.thirdparty')" :visible.sync="showDialog">
      {{ $t('login.thirdpartyTips') }}
      <br>
      <br>
      <br>
      <social-sign />
    </el-dialog> -->

    <div id="footer">
      <p
        style="
          line-height: 44px;
          text-align: center;
          margin: 0;
          font-size: 14px;
        "
      >
        软件版本：{{ versionNum }}
      </p>
    </div>
  </div>
</template>

<script>
/* import { validUsername } from '@/utils/validate' */
// import LangSelect from '@/components/LangSelect'
// import SocialSign from './components/SocialSignin'
import md5 from "js-md5";
import Cookies from "js-cookie";
import axios from "axios";
export default {
  // name: 'Login',
  // components: { LangSelect, SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      /* if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      }  */ if (value === "") {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码不能少于6位"));
      } else {
        callback();
      }
    };
    return {
      versionNum: process.env.VUE_APP_VERSION_NUM, // 项目版本号
      showHospital: false,
      loginForm: {
        username: "",
        password: "",
        md5Psd: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      oRemember: false,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        // console.log(route)

        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
          // console.log(this.otherQuery)
        }
      },
      immediate: true,
    },
  },
  created() {
    let loginIP = process.env.VUE_APP_BASE_API_LOGIN;
    this.showHospital = loginIP.includes("112.26.177.46");
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.loginForm.md5Psd = md5(this.loginForm.password);
          /* *******************记住密码，7天有效期 ***************** */
          if (this.oRemember) {
            Cookies.set("username", this.loginForm.username, { expires: 7 });
            Cookies.set("password", this.loginForm.password, { expires: 7 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
          }
          /* **************** */


          this.$store
            .dispatch("user/login", this.loginForm)
            .then((res) => {
              location.reload();
              console.log(res, "res");
              this.$router.push({
                path: this.redirect || "/",
                query: this.otherQuery,
              });
              this.loading = false;
            })
            .catch(() => {
              this.$message.error("用户或密码错误！");
              // if (err.response.data.code.toString() === '400') {
              //   this.$message.error('用户名或密码错误')
              // } else if (err.response.data.code.toString() === '401') {
              //   this.$message.error('用户不存在')
              // } else if (err.response.data.code.toString() === '403') {
              //   this.$message.error('验证失败')
              // } else {
              //   this.$message.error('服务器异常  ' + err.response.data.error_description)
              // }
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      // console.log(Object.keys(query))

      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #000;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: #000;
    // color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .hospital-title {
    font-size: 40px;
    color: #fff;
    width: 100%;
    height: 40px;
    text-align: center;
    margin-top: 25vh;
  }
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: #000;
      // color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #e8f0fe inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #000;
    // color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  // min-height: 100%;
  width: 100%;
  height: 100vh;
  background-image: url("~@/images/background.jpg");
  background-size: cover;
  position: relative;
  background-color: #f2f2f2;
  // background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    color: #000;
    max-width: 100%;
    // padding: 0 35px;
    margin: 0 auto;
    width: 450px;
    overflow: hidden;
    background-color: #fff;
    margin-top: 20px;
    margin-bottom: 20px;
    border: 1px solid transparent;
    border-radius: 4px;
    -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
  }
  .panel {
  }
  .tips {
    font-size: 14px;
    color: #000;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: #000;
    // color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;
    margin-bottom: 30px;

    .title {
      font-size: 26px;
      color: #333;
      // color: $light_gray;
      // margin: 0px auto 40px auto;
      text-align: center;
      font-size: 19px;
      line-height: 50px;
      text-align: left;
      padding: 10px 15px;
      padding-top: 0px;
      height: 50px;
      border-color: #e6e6e6;
      background-color: #f5f5f5;
      border-bottom: 1px solid transparent;
      border-top-left-radius: 3px;
      border-top-right-radius: 3px;

      img {
        position: relative;
        height: 30px;
        width: 30px;
        margin-right: 5px;
        top: -3px;
        vertical-align: middle;
      }
    }

    .set-language {
      // color: #fff;
      color: #000;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: #000;
    // color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }
  #footer {
    position: absolute;
    bottom: 0.01%;
    left: 30%;
    right: 30%;
    height: 44px;
    max-height: 44px;
    background-color: transparent;
  }
  .userInfo {
    background: #e8f0fe;
    border: 1px solid #e6e6e6;
  }
  .marginLR {
    margin: 0 30px 22px;
  }
  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
</style>
